﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using Gift.WebApp;
using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;
using System.Web.UI.WebControls;


    public class BaseAdmin : System.Web.UI.Page
    {

        readonly DALAdminLogin theAdminLogin = new DALAdminLogin();
        readonly DALCompany theCompany = new DALCompany();
        readonly DALDepartment theDepartment = new DALDepartment();

        public List<UserCard> UserCardCodeList
        {
            get
            {
                if (Session["UserCardCodeList"] != null)
                {
                    return (List<UserCard>)Session["UserCardCodeList"];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                Session["UserCardCodeList"] = value;
            }
        }

        public decimal TempOrderOnSale
        {
            get
            {
                if (Session["TempOrderOnSale"] != null)
                {
                    return (decimal)Session["TempOrderOnSale"];
                }
                else
                {
                    return 1;
                }
            }
            set
            {
                Session["TempOrderOnSale"] = value;
            }
 
        }

   

        public void Alert(string message)
        {
            base.ClientScript.RegisterStartupScript(base.GetType(), "sd"
                                            , string.Format( "<script language=\"javascript\" defer>alert('{0}');</script>",message)
                                            );
        }
        //public string CompanyId
        //{
        //    get
        //    {
        //        if (this.Session["CompanyId"] != null && this.Session["CompanyId"].ToString() != "")
        //        {
        //            return this.Session["CompanyId"].ToString();
        //        }
        //        else
        //        {
        //            return null;
        //        }
        //    }
        //    set
        //    {
        //        this.Session["CompanyId"] = value;
        //    }
        //}

        //public string CompanyLevelId
        //{
        //    get
        //    {
        //        if (this.Session["CompanyLevel"] != null)
        //        {
        //            return this.Session["CompanyLevel"].ToString();
        //        }
        //        else
        //        {
        //            return "0";
        //        }
        //    }
        //    set
        //    {
        //        this.Session["CompanyLevel"] = value;
        //    }
        //}

        public string OrderId
        {
            get
            {
                if (this.Session["OrderId"] != null)
                {
                    return this.Session["OrderId"].ToString();
                }
                else
                {
                    return null;
                }
            }
            set
            {
                this.Session["OrderId"] = value;
            }
        }


        void GetLoginUser()
        {
            if (Request.QueryString["admin"] != null)
            {
                string usn = re.replace(Request.QueryString["admin"]);
                string pwd = re.EncodeMD5(Request.QueryString["pass"]);
                bool isLogin = login.lo(usn, pwd);
                if (isLogin)
                {
                    LoginAdmin oLoginAdmin = new LoginAdmin();
                    tbAdminLogin o = theAdminLogin.GetModel(usn, pwd);
                    if (o.AdminFlag == 0)
                    {
                        HttpContext.Current.Response.Write("<script>alert('用户账户已停用或未启用，请联系管理员！');</script>");
                        return;
                    }
                    oLoginAdmin.AdminUser = o.AdminUser;
                    oLoginAdmin.AdminUserId = o.AdminId.ToString();
                    oLoginAdmin.AdminTypeId = o.AdminTypeId.ToString();
                    tbCompany oCompany;
                    if (o.DepartmentID == 0)
                    {
                        oCompany = this.theCompany.GetModelByAdminId(int.Parse(oLoginAdmin.AdminUserId));
                        oLoginAdmin.CompanyAdminId = oLoginAdmin.AdminUserId;
                        oLoginAdmin.CompanyId = oCompany.Id.ToString();
                    }
                    else
                    {
                        oLoginAdmin.CompanyId = this.theDepartment.GetModel(o.DepartmentID).CompanyId.ToString();
                        oCompany = this.theCompany.GetModel(int.Parse(oLoginAdmin.CompanyId));
                    }

                    oLoginAdmin.CompanyCode = oCompany.CompanyCode;
                    oLoginAdmin.CompanyLevelId = oCompany.LevelId;
                    oLoginAdmin.GoodsOnSale = oCompany.GoodsOnSale;
                    oLoginAdmin.CardOnSale = oCompany.CardOnSale;
                    new BaseAdmin().Administrator = oLoginAdmin;

                    try
                    {
                        this.Session["inphoneNumber"] = theAdminLogin.GetInphoneNumberByName(usn);
                    }
                    catch { }
                    this.Session.Timeout = 60;
                  //  Response.Redirect("index.aspx");
                }
                else
                {
                    HttpContext.Current.Response.Write("<script>alert('用户名或密码错误');</script>");
                }
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            this.GetLoginUser();

            if (Administrator == null)
            {
                base.Response.Write("<script language=javascript>window.top.location.href='/admin/login.aspx';</script>");
                base.Response.End();
            }
        }

        public void ValidateLoginRule(ERule oRule)
        {
            if (!GetValidateLoginRule(oRule))
            {

                base.Response.Write("<script language=javascript>window.top.location.href='/admin/login.aspx';</script>");
                base.Response.End();
            }

        }

  

        public LoginAdmin Administrator
        {
            get
            {
                if (this.Session["LoginAdmin"] != null)
                {
                    return this.Session["LoginAdmin"] as LoginAdmin;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                this.Session["LoginAdmin"] = value;
            }
        }



        public bool GetValidateLoginRule(ERule oRule)
        {
            int iAdminId = int.Parse(Administrator.AdminUserId);
            DataSet ds;

            if (iAdminId.ToString() == Administrator.CompanyAdminId)
            {
                ds = BaseFactory.theRoleRuleRef.GetListByCompanyIdForCompany(int.Parse(Administrator.CompanyId));
                if (ds != null && ds.Tables.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        if (dr["Name"].ToString() == oRule.ToString())
                        {
                            return true;
                        }
                    }
                }
            }
            else
            {
                DataSet dsRoles = BaseFactory.theRoleRuleRef.GetRoleListByAdminId(iAdminId);

                if (dsRoles != null && dsRoles.Tables.Count > 0)
                {
                    foreach (DataRow drRole in dsRoles.Tables[0].Rows)
                    {
                        ds = BaseFactory.theRoleRuleRef.GetListByRoleId(int.Parse(drRole["id"].ToString()));
                        if (ds != null && ds.Tables.Count > 0)
                        {
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                if (dr["Name"].ToString() == oRule.ToString())
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            

          


            return false;

        }
        protected DataTable GetAllCompany(DataTable dtSource, DataTable dtTarget, int parentId, bool isViewAllDownCompany)
        {
            DataRow drTaget;
            if (dtTarget == null)
            {
                dtTarget = dtSource.Clone();

                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    if (dtSource.Rows[i]["Id"].ToString() == parentId.ToString())
                    {
                        drTaget = dtTarget.NewRow();
                        drTaget.ItemArray = dtSource.Rows[i].ItemArray;
                        dtTarget.Rows.Add(drTaget);
                    }
                }
            }

            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                if (dtSource.Rows[i]["ParentId"].ToString() == parentId.ToString())
                {
                    drTaget = dtTarget.NewRow();
                    drTaget.ItemArray = dtSource.Rows[i].ItemArray;
                    dtTarget.Rows.Add(drTaget);

                    if (isViewAllDownCompany)
                    {
                        for (int m = 0; m < dtSource.Rows.Count; m++)
                        {
                            if (dtSource.Rows[m]["ParentId"].ToString() == dtSource.Rows[i]["Id"].ToString())
                            {
                                drTaget = dtTarget.NewRow();
                                drTaget.ItemArray = dtSource.Rows[m].ItemArray;
                                dtTarget.Rows.Add(drTaget);

                                for (int n = 0; n < dtSource.Rows.Count; n++)
                                {
                                    if (dtSource.Rows[n]["ParentId"].ToString() == dtSource.Rows[m]["Id"].ToString())
                                    {
                                        drTaget = dtTarget.NewRow();
                                        drTaget.ItemArray = dtSource.Rows[n].ItemArray;
                                        dtTarget.Rows.Add(drTaget);

                                        for (int h = 0; h < dtSource.Rows.Count; h++)
                                        {
                                            if (dtSource.Rows[h]["ParentId"].ToString() == dtSource.Rows[n]["Id"].ToString())
                                            {
                                                drTaget = dtTarget.NewRow();
                                                drTaget.ItemArray = dtSource.Rows[h].ItemArray;
                                                dtTarget.Rows.Add(drTaget);

                                                for (int q = 0; q < dtSource.Rows.Count; q++)
                                                {
                                                    if (dtSource.Rows[q]["ParentId"].ToString() == dtSource.Rows[h]["Id"].ToString())
                                                    {
                                                        drTaget = dtTarget.NewRow();
                                                        drTaget.ItemArray = dtSource.Rows[q].ItemArray;
                                                        dtTarget.Rows.Add(drTaget);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return dtTarget;


        }


        protected void SetListPerssion(RepeaterItemEventArgs e, bool isEdit)
        {

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (!isEdit)
                {
                    e.Item.FindControl("divEdit").Visible = false;
                }
            }

        }

        protected void SetListPerssion(RepeaterItemEventArgs e,bool isEdit,bool isDeleted)
        {

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (!isEdit)
                {
                    e.Item.FindControl("divEdit").Visible = false;
                }
                if (!isDeleted)
                {
                    e.Item.FindControl("divDeleted").Visible = false;
                }
            }

        }

        protected void SetListPerssion(RepeaterItemEventArgs e, bool isEdit, bool isDeleted,bool isPermission)
        {

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (!isEdit)
                {
                    e.Item.FindControl("divEdit").Visible = false;
                }
                if (!isDeleted)
                {
                    e.Item.FindControl("divDeleted").Visible = false;
                }
                if (!isPermission)
                {
                    e.Item.FindControl("divPermission").Visible = false;
                }
            }
        }

        protected void SetGridListPerssion(GridViewRowEventArgs e, bool isEdit, bool isDeleted, bool isUser)
        {

           if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (!isEdit)
                {
                    e.Row.FindControl("divEdit").Visible = false;
                }
                if (!isDeleted)
                {
                    e.Row.FindControl("divDeleted").Visible = false;
                }
                if (!isUser)
                {
                    e.Row.FindControl("divUser").Visible = false;
                }
            }
        }

    }

[Serializable]
    public class LoginAdmin
    {
        string _adminUser = null;

        public string AdminUser
        {
            get { return _adminUser; }
            set { _adminUser = value; }
        }

        string _adminUserId = null;

        public string AdminUserId
        {
            get { return _adminUserId; }
            set { _adminUserId = value; }
        }

        string _adminTypeId = null;

        public string AdminTypeId
        {
            get { return _adminTypeId; }
            set { _adminTypeId = value; }
        }

        string _companyId = null;

        public string CompanyId
        {
            get { return _companyId; }
            set { _companyId = value; }
        }
        string _companyCode = null;

        public string CompanyCode
        {
            get { return _companyCode; }
            set { _companyCode = value; }
        }

        string _companyAdminId = null;

        public string CompanyAdminId
        {
            get { return _companyAdminId; }
            set { _companyAdminId = value; }
        }

        int _companyLevelId = 4;

        public int CompanyLevelId
        {
            get { return _companyLevelId; }
            set { _companyLevelId = value; }
        }
        float _goodsOnSale;

        public float GoodsOnSale
        {
            get { return _goodsOnSale; }
            set { _goodsOnSale = value; }
        }
        float _cardOnSale;

        public float CardOnSale
        {
            get { return _cardOnSale; }
            set { _cardOnSale = value; }
        }

        string _meteriaOrderCardIds;

        public string MeteriaOrderCardIds
        {
            get { return _meteriaOrderCardIds; }
            set { _meteriaOrderCardIds = value; }
        }
    }


